using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[DisallowMultipleComponent]
public class DealContactDamage : MonoBehaviour
{
    #region Header DEAL DAMAGE

    [Space(10)]
    [Header("造成伤害")]

    #endregion

    #region Tooltip

    [Tooltip("要处理的触点损坏（由接收器覆盖）")]

    #endregion

    [SerializeField]
    private int contactDamageAmount;

    #region Tooltip

    [Tooltip("指定对象应位于哪些层上以承受接触损坏")]

    #endregion

    [SerializeField]
    private LayerMask layerMask;

    private bool isColliding = false;

    // 进入碰撞体时触发接触损坏
    private void OnTriggerEnter2D(Collider2D collision)
    {
        // 如果已经与某物发生碰撞，请返回
        if (isColliding) return;

        ContactDamage(collision);
    }

    // 当停留在碰撞体内时触发接触损坏
    private void OnTriggerStay2D(Collider2D collision)
    {
        // 如果已经与某物发生碰撞，请返回
        if (isColliding) return;

        ContactDamage(collision);
    }

    private void ContactDamage(Collider2D collision)
    {
        // 如果碰撞对象不在指定层中，则返回（使用按位比较）
        int collisionObjectLayerMask = (1 << collision.gameObject.layer);

        if ((layerMask.value & collisionObjectLayerMask) == 0)
            return;

        // 检查碰撞物体是否应受到接触损坏
        ReceiveContactDamage receiveContactDamage = collision.gameObject.GetComponent<ReceiveContactDamage>();

        if (receiveContactDamage != null)
        {
            isColliding = true;

            // 在设定时间后重置触点冲突
            Invoke("ResetContactCollision", Settings.contactDamageCollisionResetDelay);

            receiveContactDamage.TakeContactDamage(contactDamageAmount);
        }
    }

    /// <summary>
    /// 重置 isColliding bool
    /// </summary>
    private void ResetContactCollision()
    {
        isColliding = false;
    }

    #region Validation

#if UNITY_EDITOR
    private void OnValidate()
    {
        HelperUtilities.ValidateCheckPositiveValue(this, nameof(contactDamageAmount), contactDamageAmount, true);
    }
#endif

    #endregion
}